<template lang="html">
  <div class="main">
      <div class="main-group">
        <div class="main-body body-left">
          <div class="title">
            轨迹图
          </div>
          <div class="body">
            <div id="test_chart" class="chart">
            </div>
          </div>
        </div>
        <div class="main-body body-right">
          <div class="title">
            预警信息
          </div>
          <div class="body">
            <div class="message">
              我是警告信息
            </div>
          </div>
        </div>
      </div>
    <div class="main-menu">
      <div class="menu">
        <span @click="back">上一个</span>
        <span @click="back">返回</span>
        <span @click="back">下一个</span>
      </div>
    </div>
  </div>
</template>

<script>
import { lazyAMapApiLoaderInstance } from 'vue-amap';
// let map = {};
export default {
  data () {
    return {
      showamap: false,
      persons: [],
      map: null,
      runIndex: 0,
      pathSimplifierIns: false
    };
  },
  methods: {
    back () {
      this.$router.go(-1);
    },
    draw () {
    },
    addPosition () {
      // 创建一个 Marker 实例：
      var marker = new AMap.Marker({
        position: new AMap.LngLat(121.59996, 31.197646), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: '北京'
      });
      // 将创建的点标记添加到已有的地图实例：
      this.map.add(marker);
    },
    createInfoWindow (title, content) {
      // 关闭信息窗体
      let closeInfoWindow = () => {
        this.map.clearInfoWindow();
      };
      // 构建自定义信息窗体
      let createInfoWindow = (title, content) => {
        var info = document.createElement('div');
        info.className = 'info';
        // 可以通过下面的方式修改自定义窗体的宽高
        // info.style.width = "400px";
        // 定义顶部标题
        var top = document.createElement('div');
        var titleD = document.createElement('div');
        var closeX = document.createElement('img');
        top.className = 'info-top';
        titleD.innerHTML = title;
        closeX.src = 'https://webapi.amap.com/images/close2.gif';
        closeX.onclick = closeInfoWindow;

        top.appendChild(titleD);
        top.appendChild(closeX);
        info.appendChild(top);

        // 定义中部内容
        var middle = document.createElement('div');
        middle.className = 'info-middle';
        middle.style.backgroundColor = 'white';
        middle.innerHTML = content;
        info.appendChild(middle);

        // 定义底部内容
        var bottom = document.createElement('div');
        bottom.className = 'info-bottom';
        bottom.style.position = 'relative';
        bottom.style.top = '0px';
        bottom.style.margin = '0 auto';
        var sharp = document.createElement('img');
        sharp.src = 'https://webapi.amap.com/images/sharp.png';
        bottom.appendChild(sharp);
        info.appendChild(bottom);
        return info;
      };
      return createInfoWindow(title, content);
    },
    addInfoWinodw (person) {
      // 实例化信息窗体
      let title = `<span style="color: red;">${person.name}</span>购买药品信息`;
      let content = [];
      content.push(`<img src='https://tpc.googlesyndication.com/simgad/5843493769827749134'>药品名称：${person.buyName}`);
      content.push(`药店数量：${person.buyNum}`);
      content.push(`药店地址：上海市xxxx`);
      content.push('<br/>');

      return new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: this.createInfoWindow(title, content.join('<br/>')),
        offset: new AMap.Pixel(16, -30)
      });
    },
    setRun (thisRun) {
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！');
          return;
        }
        if (!this.pathSimplifierIns) {
          this.pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            // autoSetFitView:false,
            map: this.map, // 所属的地图实例
            getPath: function (pathData, pathIndex) {
              return pathData.path;
            },
            getHoverTitle: (pathData, pathIndex, pointIndex) => {
              if (pointIndex >= 0) {
                return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
              }
              return pathData.name + '，点数量' + pathData.path.length;
            },
            renderOptions: {
              pathLineStyle: {
                dirArrowStyle: true
              },
              getPathStyle: function (pathItem, zoom) {
                let color = '#9932CC';
                let lineWidth = 5;

                return {
                  pathLineStyle: {
                    strokeStyle: color,
                    lineWidth: lineWidth
                  },
                  pathLineSelectedStyle: {
                    lineWidth: lineWidth + 2
                  },
                  pathNavigatorStyle: {
                    fillStyle: color
                  }
                };
              },
              renderAllPointsIfNumberBelow: 100 // 绘制路线节点，如不需要可设置为-1
            }
          });
        }

        // 设置数据
        this.pathSimplifierIns.setData([{
          name: '路线0',
          path: thisRun
        }]);

        // 对第一条线路（即索引 0）创建一个巡航器
        var navg1 = this.pathSimplifierIns.createPathNavigator(0, {
          loop: false, // 循环播放
          speed: 10000, // 巡航速度，单位千米/小时
          pathNavigatorStyle: {
            // autoRotate: false, // 禁止调整方向
            pathLinePassedStyle: {
              'lineWidth': 5,
              'strokeStyle': '#999999',
              'borderWidth': 1,
              'borderStyle': '#eeeeee',
              'dirArrowStyle': false
            },
            width: 24,
            height: 24,
            // content: PathSimplifier.Render.Canvas.getImageContent('./imgs/car-front.png', onload, onerror),
            strokeStyle: '#0000FF',
            fillStyle: '#0000FF'
          }
        });

        navg1.start();
      });
    },
    setMap () {
      // massMarks.setMap(this.map);
      AMapUI.loadUI(['misc/PointSimplifier'], (PointSimplifier) => {
        if (!PointSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！');
          return;
        }
        let initPage = (PointSimplifier) => {
          // 创建组件实例
          var pointSimplifierIns = new PointSimplifier({
            map: this.map, // 关联的map
            compareDataItem: function (a, b, aIndex, bIndex) {
            // 数据源中靠后的元素优先，index大的排到前面去
              return aIndex > bIndex ? -1 : 1;
            },
            getPosition: function (dataItem) {
            // 返回数据项的经纬度，AMap.LngLat实例或者经纬度数组
              return dataItem.position;
            },
            getHoverTitle: function (dataItem, idx) {
            // 返回数据项的Title信息，鼠标hover时显示
              return '序号: ' + idx;
            },
            renderOptions: {
            // 点的样式
              pointStyle: {
                fillStyle: 'blue' // 蓝色填充
              }
            }
          });

          // 随机创建一批点，仅作示意
          var data = createPoints(this.map.getCenter(), 15);

          // 设置数据源，data需要是一个数组
          pointSimplifierIns.setData(data);

          // 监听事件
          pointSimplifierIns.on('pointClick', (e, record) => {
            console.log(e, record);
            let win = this.addInfoWinodw(this.persons[record.index]);
            let position = record.data.position;
            win.open(this.map, position);
          });
        };
        let names = ['张三', '李四', '王五', '赵六', '李七'];
        // 仅作示意
        let createPoints = (center, num) => {
          var data = [];
          for (var i = 0, len = num; i < len; i++) {
            let p = [
              center.getLng() + (Math.random() > 0.5 ? 1 : -1) * Math.random() * 0.1,
              center.getLat() + (Math.random() > 0.5 ? 1 : -1) * Math.random() * 0.1
            ];
            console.log(p);
            if (i % 10 === 0) {
              // this.thisRun.push(p);
            }
            this.persons.push({id: i, name: names[i % 5], buyNum: 10, buyName: 'xxx', p});
            data.push({
              position: p
            });
          }
          return data;
        };
        // 启动页面
        initPage(PointSimplifier);
        this.startRun();
      });
    },
    startRun () {
      if (this.runIndex >= 5) {
        this.runIndex = 0;
      }
      console.log('this.persons', this.persons.length, this.persons.find(p => p.id % 5 === this.runIndex));
      let position = this.persons.filter(p => p.id % 5 === this.runIndex).map(p => {
        return p.p;
      });
      this.setRun(position);
      this.runIndex++;
      setTimeout(this.startRun, 20000);
    }
  },
  mounted () {
    setTimeout(_ => {
      this.showamap = true;
      lazyAMapApiLoaderInstance.load().then(() => {
        this.map = new AMap.Map('test_chart', {
          resizeEnable: false,
          features: ['bg', 'road'],
          center: [121.59996, 31.197646],
          zooms: [9, 18], // 设置地图级别范围
          zoom: 9
        });
        // this.addPosition();
        this.setMap();
      });
    }, 600);
  }
};
</script>

<style lang="css" scoped>
.main {
  background-image: url('../../assets/bg_all_2.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  vertical-align: middle;
  justify-content: center;
  align-items: center;
  text-align: center;
  .main-group {
    width: 70%;
    height: 70%;
    display: flex;
    flex-direction: row;
    align-items: stretch;
    .main-body {
      margin-left: 20px;
      box-shadow: 2px 6px 12px 2px rgba(0,0,0,.8);
      border-radius: 4px;
      border: 3px solid #ebeef5;
      background-color: rgba(255,255,255,.95);
      overflow: hidden;
      color: #303133;
      transition: .3s;
      .title {
        position: relative;
        height: 60px;
        line-height: 60px;
        text-align: left;
        margin-left: 20px;
        margin-right: 20px;
      }
      .title::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 3px;
        top: 100%;
        left: 0px;
        overflow: hidden;
        border-top: 1px solid  rgba(150,150,150,.5);
        border-bottom: 1px solid  rgba(255,255,255,1);
        background-color: #eee;
      }
      .body {
        padding: 10px;
        height: 100%;
        width: 100%;
        position: relative;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        .chart {
          width: 100%;
          height: 100%;
        }
      }
    }
    .main-body:first-child {
      margin-left: 0px;
    }
    .body-left {
      width: 70%;
    }
    .body-right {
      width: 30%;
    }
  }
  .main-menu {
    width: 70%;
    height: 50px;
    margin-top: 15px;
    position: relative;
    .menu {
      font-size: 20px;
      font-family: '微软雅黑';
      color: rgba(255,255,255,0.5);
      display: flex;
      flex-direction: row;
      vertical-align: middle;
      justify-content: center;
      align-items: center;
      text-align: center;
      height: 100%;
      margin-left: 30%;
      margin-right: 30%;
      span {
        display: block;
        flex: 1;
        cursor: pointer;
      }
      span:hover {
        transition: all .3s;
        font-size: 26px;
      }
    }
    .menu::after {
      content: '';
      position: absolute;
      width: 50%;
      height: 20px;
      top: 100%;
      overflow: hidden;
      background-size:100% 100%;
      background-image: url('../../assets/pic_back_tips.png');
    }
  }
}
</style>
<style media="screen">
.info {
    border: solid 1px silver;
    min-width: 250px;
}
div.info-top {
    position: relative;
    background: none repeat scroll 0 0 #F9F9F9;
    border-bottom: 1px solid #CCC;
    border-radius: 5px 5px 0 0;
}
div.info-top div {
    display: inline-block;
    color: #333333;
    font-size: 14px;
    font-weight: bold;
    line-height: 31px;
    padding: 0 10px;
}
div.info-top img {
    position: absolute;
    top: 10px;
    right: 10px;
    transition-duration: 0.25s;
}
div.info-top img:hover {
    box-shadow: 0px 0px 5px #000;
}
div.info-middle {
    font-size: 12px;
    padding: 6px;
    line-height: 20px;
    text-align: left;
}
div.info-bottom {
    height: 0px;
    width: 100%;
    clear: both;
    text-align: center;
}
div.info-bottom img {
    position: relative;
    z-index: 104;
}
.info-middle img {
    float: left;
    margin-right: 6px;
}
</style>
